{extend name="admin@public/basic" /}

{block name="style"}
<link rel="stylesheet" href="__STATIC__/css/admin/public.css" media="all"/>
{/block}

{block name="cotent"}
<form class="layui-form">

    <!--顶部操作栏--开始-->
    <blockquote id="searchBlock" class="layui-elem-quote quoteBox">


        <div class="layui-form-item layui-inline">
            <a class="layui-btn" data-href='/static/uploads/住户信息导入模版.xls'>下载模版</a>
        </div>

        <div class="layui-form-item layui-inline" style="position: relative;">
            <input type="file" id="importFile" style="width: 100%; height: 100%; position: absolute; top:0; opacity: 0; cursor: pointer;" />
            <a class="layui-btn" id="import">导入</a>
        </div>

    </blockquote>
    <!--顶部操作栏--结束-->
    <div>导入历史：</div>
    <!--主表单渲染--开始-->
    <table id="currentTable" lay-filter="currentTable"></table>
    <!--主表单渲染--结束-->

    <!--表单模板绑定--开始-->
    <script type="text/html" id="bindMemberInfo">
        <div>
            <span>{{d.nickname}}</span> <a class="layui-btn layui-btn-xs color-admin-desc" data-open='{:url("@admin/article.member/detail")}?id={{d.member_id}}' data-title="查看会员信息" data-width="1000px" data-height="450px">{{d.username}}</a>
        </div>
    </script>

    <script type="text/html" id="bindImage">
        <img style="width: 60px; height: 40px;" src="{:CDNDomain()}{{d.image ? d.image : '/static/image/admin/face.png'}}" layer-src="{:CDNDomain()}{{d.image}}" alt="{{d.name}}" data-image="open" lay-filter="modifyHeadImg">
    </script>
    <!-- 启用禁用 -->
    <script type="text/html" id="checkStatus">
        {{ d.status== 0 ? '<span class="layui-badge-rim">未完成</span>' : '<span class="layui-badge-rim layui-bg-green">已完成</span>' }}

    </script>
    <!-- 是否推荐 -->
        <script type="text/html" id="checkPosition">
            {{ d.is_pos== 0 ? '<span class="layui-badge-rim">否</span>' : '<span class="layui-badge-rim layui-bg-green">是</span>' }}
        </script>
    <!-- 是否删除 -->
    <script type="text/html" id="checkDeleted">
        {{ d.is_deleted== 0 ? '<span class="layui-badge-rim">否</span>' : '' }}
    </script>
    <!--表单模板绑定--结束-->

    <!--表单操作栏--开始-->
    <script type="text/html" id="currentTableBar">


        {if auth("$thisClass/edit")}
        <a class="layui-btn layui-btn-xs" data-title="修改信息" data-id="{{d.id}}" onclick="exportRecord('{{d.id}}')">下载表格</a>
        {/if}

        {if auth("$thisClass/del")}
        <a class="layui-btn layui-btn-xs layui-btn-danger" data-id="" onclick="exportErrRecord('{{d.id}}')">下载失败数据</a>
        {/if}

    </script>
    <!--表单操作栏--结束-->

</form>

<form class="layui-form" id="cm-form"><div class="layui-form-item"><select id="cm">'+str+'</select></div></form>'
{/block}

{block name="script"}
<script>

    /**
     * 生成表单
     */
    $.form.table('current', '{:url("$thisRequest")}?type=ajax', [[
        {type: 'checkbox', width: 50, fixed: 'left'},
                        {field: 'id', title: '编号',align: 'center'},
                        {field: 'name', title: '导入表格名称',align: 'center'},
                        {field: 'createtime', title: '导入时间',align: 'center'},
        {field: 'err_msg', title: '失败/总数',align: 'center'},
        {field: 'user', title: '操作人',align: 'center'},
                        {field: 'status', title: '导入状态',align: 'center',width: 110, templet: '#checkStatus', unresize: true},
                        {field: 'is_deleted', title: '是否删除',align: 'center',width: 110, templet: '#checkDeleted', unresize: true},
                        {field:'id',title: '操作', minWidth: 160, templet: '#currentTableBar', fixed: 'right', align: 'center'},
    ]], true, 'line', 'lg', true);
    /**
     * 日期范围
     */
    $.laydate.range('create_at');

    // todo 先选择小区
    layui.use('form', function() {
        var form = layui.form;
        getAllCmMessage(form);
    })

    function getAllCmMessage(form) {
        $.ajax({
            url: '{:url("housekeep.CmMessage/getAllCmMessage")}',
            success: function(res) {
                console.log(res);
                for(var i in res.data) {
                    var str = '<option value="'+res.data[i].id+'">'+res.data[i].name+'</option>';
                    $('#cm').append(str);
                }
                form.render();
                var open = layer.open({
                    type: 1,
                    area: ['auto', '200px'],
                    content: $('#cm-form'),
                    title: '请选择要导入的小区',
                    closeBtn: 0
                });
                form.on('select', function(data) {
                    var value = data.value;
                    console.log(data);
                    $.ajax({
                        url: '{:url("housekeep.CmMessage/getUserSetCm")}',
                        data: {
                            cmId: data.value
                        },
                        success: function(res) {
                            if(res.code == 0) {
                                layer.msg(res.msg);
                                setTimeout(function() {
                                    layer.close(open);
                                }, 1000);
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    })
                })
            }
        })
    }

    /**
     * 修改状态
     */
    $.form.switch('modifyStatus', '{:url("$thisClass/status")}');
    $('#importFile').change(function(e) {
        var file = e.delegateTarget.files[0];
        var suffix = file.name.trim().split('.')[1];
        console.log(suffix);
        if(suffix == 'xls' || suffix == 'excel' || suffix == 'xlsx') {
            var formData = new FormData();
            formData.append('file', file);
            $.ajax({
                url: '{:url("$thisClass/importFile")}',
                data: formData,
                cache:false,
                processData:false,
                contentType:false,
                dataType:"json",
                method: 'post',
                success: function(res) {
                    $.msg.success(res.msg, function () {
                        $.tool.reload();
                    });
                }
            })
        } else {
            layer.msg('请上传正确的格式');
        }
    })

    /**
     * 导入历史导出
     */
    function exportRecord(recordid) {
        var searchData = Object();
        var searchInput = $('#searchBlock div div input');
        var searchSelect = $('#searchBlock div div select');
        $.each(searchInput, function (i, obj) {
            id = $(obj).attr('id');
            if (id != undefined) {
                searchData[id] = $("#" + id).val();
            }
        });
        $.each(searchSelect, function (i, obj) {
            id = $(obj).attr('id');
            if (id != undefined) {
                searchData[id] = $("#" + id).val();
            }
        });
        var flag = new Date().getTime();

        var search = searchData;

        var page=1;
        layer.load(2,{shade: [0.5,'#fff']});
        layer.msg('正在准备导出,请耐心等待',{time: 5000});
        explorecel(page,search,flag,recordid);
    }
    // $(document).on("click", "#backup", function () {
    //
    //
    // });
    function explorecel(page,search,flag,recordid) {
        console.log(search);
        $.get('{:url("$thisClass/index_exp")}',
            {
                type:'export',
                page:page,
                search:search,
                flag:flag,
                id: recordid
            },
            function(data){
                layer.msg(data.msg);
                if(data.code==0){
                    setTimeout(function () {
                        explorecel(data.page,search,flag);
                    },1400)
                } else if(data.code == 2){
                    layer.closeAll();
                    window.location.href = data.url;
                } else {
                    setTimeout(function () {
                        layer.closeAll();
                    },1400)
                }
            }, "json");
    }


    /**
     * 导入错误记录
     */
    function exportErrRecord(recordid) {
        var searchData = Object();
        var searchInput = $('#searchBlock div div input');
        var searchSelect = $('#searchBlock div div select');
        $.each(searchInput, function (i, obj) {
            id = $(obj).attr('id');
            if (id != undefined) {
                searchData[id] = $("#" + id).val();
            }
        });
        $.each(searchSelect, function (i, obj) {
            id = $(obj).attr('id');
            if (id != undefined) {
                searchData[id] = $("#" + id).val();
            }
        });
        var flag = new Date().getTime();

        var search = searchData;

        var page=1;
        layer.load(2,{shade: [0.5,'#fff']});
        layer.msg('正在准备导出,请耐心等待',{time: 5000});
        explorecelErr(page,search,flag,recordid);

    }
    // $(document).on("click", "#backupErr", function () {
    //
    // });
    function explorecelErr(page,search,flag,recordid) {
        console.log(search);
        $.get('{:url("$thisClass/index_err_exp")}',
            {
                type:'export',
                page:page,
                search:search,
                flag:flag,
                id:recordid
            },
            function(data){
                layer.msg(data.msg);
                if(data.code==0){
                    setTimeout(function () {
                        explorecelErr(data.page,search,flag);
                    },1400)
                } else if(data.code == 2){
                    layer.closeAll();
                    window.location.href = data.url;
                } else {
                    setTimeout(function () {
                        layer.closeAll();
                    },1400)
                }
            }, "json");
    }

</script>
{/block}
